<template>
  <el-dialog :title="dialogParams.title" :visible.sync="dialogParams.visible" :close-on-click-modal="false" width="600px" append-to-body>
    <el-form :model="formData" :rules="rules" :disabled="dialogParams.type === 'detail'" ref="formData" label-width="120px" class="demo-fileForm">
      <el-form-item label="头像上传：" prop="headImg">
        <el-upload class="avatar-uploader" :with-credentials="true" :action="`${baseURL}/v1/pc/api/file/fileUpload`" :data="uploadPrams" :show-file-list="false" :on-change="changeFile" :on-success="handleSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="formData.headImg" :src="handleImgUrl(formData.headImg)" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <img style="width: 100px; height: 100px" src="http://1.14.136.44:8082/dosm/file/image/task/7991344268843237376.jpg" alt="">
      </el-form-item>
      <el-form-item label="用户名：" prop="userName">
        <el-input v-model.trim="formData.userName" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="真实姓名：" prop="realName">
        <el-input v-model.trim="formData.realName" placeholder="请输入真实姓名"></el-input>
      </el-form-item>
      <el-form-item label="座机号码：" prop="tel">
        <el-input v-model.trim="formData.tel" placeholder="请输入座机号码"></el-input>
      </el-form-item>
      <el-form-item label="手机号码：" prop="mobile">
        <el-input v-model.trim="formData.mobile" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model.trim="formData.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="所属组织：">
        <el-select v-model="formData.orgId" clearable filterable placeholder="请选择所属组织">
          <el-option v-for="item in organizeArr" :key="item.id" :label="item.orgName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="职务：" prop="duty">
        <el-input v-model.trim="formData.duty" placeholder="请输入职务"></el-input>
      </el-form-item>
      <el-form-item label="性别：" prop="gender">
        <el-select v-model="formData.gender" placeholder="请选择">
          <el-option label="女" :value="0"></el-option>
          <el-option label="男" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出生年月：" prop="birthday">
        <el-date-picker v-model="formData.birthday" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择出生年月" :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close('formData')">取 消</el-button>
      <el-button type="primary" @click="submit('formData')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import Cookies from 'js-cookie'
import { addUser, getAllOrganize, getUserDetail, editUser } from '@/api/systemManage'
import { queryRectificationObj } from '../../../api/system'

export default {
  name: 'addUser',
  props: {
    dialogParams: {
      type: Object
    }
  },
  data() {
    return {
      pickerOptions: this.$config.pickerOptionsToday,
      organizeArr: [],
      rectificationArr: [],
      formData: {
        userName: '',
        realName: '',
        mobile: '',
        tel: '',
        email: '',
        gender: 0,
        orgId: '',
        duty: '',
        birthday: '',
        headImg: ''
      },
      rules: {
        headImg: [{ required: false, message: '请选择头像', trigger: 'blur' }],
        userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        tel: [{ required: true, message: '请输入座机号', trigger: 'blur' }],
        duty: [{ required: true, message: '请输入职务', trigger: 'blur' }]
      },
      baseURL: this.baseURL,
      uploadPrams: {
        fileType: '',
        busType: 'task'
      },
      fileList: [],
      // 文件类型
      fileType: ['jpg', 'png']
    }
  },
  created() {
    // console.log(this.dialogParams)
    this.getOrganize()
    this.getRectificationObj()
    this.getDetail()
  },
  methods: {
    handleImgUrl(url) {
      if (url) {
        if (url.indexOf('http') > -1) {
          return url
        } else {
          return this.baseURL + url
        }
      } else {
        return require('@/assets/images/default.png')
      }
    },
    // 根据id获取用户详情
    getDetail() {
      if (this.dialogParams.type != 'add' && this.dialogParams.id) {
        getUserDetail(this.dialogParams.id)
          .then(res => {
            this.formData = {
              headImg: res.headImg || '',
              userName: res.userName,
              realName: res.realName,
              mobile: res.mobile,
              tel: res.tel,
              email: res.email,
              gender: res.gender,
              orgId: res.orgId,
              duty: res.duty,
              birthday: res.birthday
            }
            if (res.headImg) {
              this.formData.headImg = this.baseURL + res.headImg
              this.fileList = [this.formData.headImg]
            }
          })
          .catch()
      }
    },
    // 获取所属组织下拉数据
    getOrganize() {
      getAllOrganize()
        .then(res => {
          this.organizeArr = res || []
        })
        .catch()
    },
    // 查询诊改对象下拉数据
    getRectificationObj() {
      queryRectificationObj()
        .then(res => {
          this.rectificationArr = res || []
        })
        .catch()
    },
    // 保存数据
    submit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          switch (this.dialogParams.type) {
            case 'add':
              addUser(this.formData)
                .then(res => {
                  if (res) {
                    this.$message.success('操作成功')
                    this.$emit('getList')
                    this.dialogParams.visible = false
                  }
                })
                .catch()
              break
            case 'edit':
              editUser(this.dialogParams.id, this.formData)
                .then(res => {
                  this.$message.success('操作成功')
                  this.$emit('getList')
                  this.dialogParams.visible = false
                })
                .catch()
          }
        } else {
          return false
        }
      })
    },
    // 关闭
    close(formName) {
      this.$refs[formName].resetFields()
      this.dialogParams.visible = false
    },
    // 改变文件
    changeFile(file) {
      if (file.raw.type.indexOf('image') != -1) {
        this.uploadPrams.fileType = 'image'
      } else {
        this.uploadPrams.fileType = 'file'
      }
    },
    handleSuccess(res, file) {
      if (res.code === 'SUCCESS') {
        this.formData.headImg = res.data
      }
    },
    fileRemove(file, fileList) {
      this.fileList = []
    },
    beforeAvatarUpload(file) {
      if (this.formData.headImg) {
        this.fileList = []
        this.formData.headImg = ''
      }

      const privateFileSize = file.size / 1024 / 1024 < 100

      if (!privateFileSize) {
        this.$message.error('上传大小不能超过 100MB!')
        return false
      }
      if (file.name.length > 30) {
        this.$message.error('文件名称太长，最多30个字')
        return false
      }
      const fileName = file.name
      const fileNameList = fileName.split('.')
      if (fileNameList.length > 1) {
        if (!this.fileType.includes(fileNameList[fileNameList.length - 1])) {
          this.$message.error('文件格式错误！请检查')
          return false
        }
      }
      if (this.fileList && this.fileList.length > 0) {
        for (let i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].name === file.name) {
            this.$message.warning('相同文件只能上传一个')
            return false
          }
        }
      }
    }
  }
}
</script>

<style scoped>
</style>
